from app.extensions import db
from app.persistence.HouseReviews import HouseReviews
from sqlalchemy import func


class ReviewService:

    @staticmethod
    def create_review(review_data):
        """创建评价"""
        try:
            review = HouseReviews(
                houseid=review_data['houseid'],
                userid=review_data['userid'],
                cleanliness_rating=review_data['cleanliness_rating'],
                location_rating=review_data['location_rating'],
                facility_rating=review_data['facility_rating'],
                value_rating=review_data['value_rating'],
                communication_rating=review_data['communication_rating'],
                comment=review_data.get('comment'),
            )
            db.session.add(review)
            db.session.commit()
            return review
        except Exception as e:
            db.session.rollback()
            raise e

    @staticmethod
    def delete_review(reviewid):
        """删除评论"""
        try:
            # 修正字段名从review_id改为reviewid
            rows_deleted = HouseReviews.query.filter_by(reviewid=reviewid).delete()
            db.session.commit()
            return rows_deleted > 0
        except Exception as e:
            db.session.rollback()
            raise e

    @staticmethod
    def update_review(reviewid, update_data):
        """更新评价"""
        try:
            review = HouseReviews.query.get(reviewid)
            if not review:
                return False

            for key, value in update_data.items():
                if hasattr(review, key):
                    setattr(review, key, value)

            db.session.commit()
            return True
        except Exception as e:
            db.session.rollback()
            raise e

    @staticmethod
    def get_review(reviewid):
        """获取单个评价"""
        return HouseReviews.query.get(reviewid)

    @staticmethod
    def is_review_owner(reviewid, userid):
        """验证评价是否属于指定用户"""
        review = HouseReviews.query.get(reviewid)
        return review and review.userid == userid

    @staticmethod
    def get_house_reviews(houseid, page=1, per_page=10):
        """获取房源的评价列表"""
        return ReviewService._get_reviews(
            HouseReviews.query.filter_by(houseid=houseid),
            page,
            per_page
        )

    @staticmethod
    def get_user_reviews(userid, page=1, per_page=10):
        """获取用户的评价列表"""
        return ReviewService._get_reviews(
            HouseReviews.query.filter_by(userid=userid),
            page,
            per_page
        )

    @staticmethod
    def _get_reviews(query, page=1, per_page=10):
        """内部方法：处理评价查询并格式化结果"""
        pagination = query.paginate(page=page, per_page=per_page)

        reviews = []
        for review in pagination.items:
            review_data = {
                'reviewid': review.reviewid,
                'houseid': review.houseid,
                'userid': review.userid,
                'cleanliness_rating': review.cleanliness_rating,
                'location_rating': review.location_rating,
                'facility_rating': review.facility_rating,
                'value_rating': review.value_rating,
                'communication_rating': review.communication_rating,
                'comment': review.comment,
                'review_time': review.review_time.isoformat(),
                # 计算平均评分
                'average_rating': (
                                          review.cleanliness_rating +
                                          review.location_rating +
                                          review.facility_rating +
                                          review.value_rating +
                                          review.communication_rating
                                  ) / 5,
            }
            reviews.append(review_data)

        return {
            'reviews': reviews,
            'total': pagination.total,
            'pages': pagination.pages,
            'current_page': page
        }

    @staticmethod
    def calculate_house_average_rating(houseid):
        """计算房源的平均评分（修正版）"""
        reviews = HouseReviews.query.filter_by(houseid=houseid).all()

        if not reviews:
            return 0.0

        # 计算每条评论的平均分，再汇总取平均
        total_avg_ratings = sum([
            (review.cleanliness_rating +
             review.location_rating +
             review.facility_rating +
             review.value_rating +
             review.communication_rating) / 5.0
            for review in reviews
        ])

        return round(total_avg_ratings / len(reviews), 1)